<template>
    <div id="email-history" class="main">
        <el-row style="height: calc(50% - 58px)">
            <vxe-table
                ref="table"
                :data="dataSource"
                v-loading="loading"
                :row-config="{ isHover: true }"
                :resizable-config="{ minWidth: '80' }"
                :sort-config="{ defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] }, remote: true }"
                :filter-config="{ remote: true }"
                @filter-change="handleFilter"
                @sort-change="handleSort"
                @cell-click="handleRowClick"
                height="100%"
                style="min-height: 200px"
                header-align="center"
                highlight-hover-row
                highlight-current-row
                auto-resize
                show-header-overflow
                resizable
                stripe
                border
            >
                <vxe-column
                    v-for="item in columns"
                    :field="item.val"
                    :title="item.name"
                    :key="item.val"
                    :filters="item.filters"
                    :align="item.align"
                    :min-width="item.minWidth || '90px'"
                    :width="item.width"
                    show-overflow="tooltip"
                    sortable
                >
                    <template #filter="{ $panel, column }" v-if="!checkFiltersParams.includes(item.val)">
                        <div>
                            <el-input
                                ref="searchInput"
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </div>
                    </template>
                    <template slot-scope="scope">
                        <span v-if="item.type == 'func'" :style="getStyle(item.val, scope.row[item.val])">
                            {{ item.funcBody(scope.row[item.val]) || '--' }}
                        </span>
                        <span v-else>
                            {{ scope.row[item.val] === 0 || (scope.row[item.val] && (scope.row[item.val] + '').trim()) ? scope.row[item.val] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
        </el-row>
        <div>
            <RiskPagination :paging="paging" @page-change="getEmailHistoryList"></RiskPagination>
        </div>
        <el-row class="html-box">
            <EmailContent :recordDetail="recordDetail" />
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import RiskPagination from '@/common/components/risk-pagination.vue';
import EmailContent from './email-content.vue';
import { dateFormat, getConfigItem, timeFormat } from '@/utils/tools';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
    totalPage?: number;
}

const noticeTypeStorage: any = {
    '0': '风险监控屏通知',
    // '1': '条目监控',
    // '2': '上游连接状态',
    // '3': '引擎初始化',
    // '4': '引擎运行状态',
    // '5': 'CDC运行监听',
    '6': '风险报告结果',
    '12': '风险计算异常',
    '9': '条目同步黑白名单启停',
    '10': '条目同步黑白名单更新',
    '13': '分项授信额度通知',
    '15': '触发提醒类',
};

const sendStatusStorage: any = {
    '0': '发送成功',
    '1': '发送失败',
};

@Component({
    name: 'EmailHistory',
    components: { RiskPagination, EmailContent },
})
export default class EmailHistory extends Vue {
    @Prop() data: any;

    private dataSource: any[] = [];
    private loading: boolean = false;
    private paging: pages = { currentPage: 1, pageSize: 20, totalPage: 0, total: 0 };
    private columns: any[] = [
        {
            name: '发送编号',
            val: 'recordId',
            align: 'left',
            filters: [{ data: '' }],
        },
        {
            name: '规则编号',
            val: 'ruleId',
            align: 'left',
            // filters: [{ data: '' }],
        },
        {
            name: '规则名称',
            val: 'ruleName',
            align: 'left',
            filters: [{ data: '' }],
        },
        {
            name: '通知类型',
            val: 'noticeType',
            align: 'center',
            minWidth: '140px',
            filters: [
                { label: '风险监控屏通知', value: '0' },
                // { value: '1', label: '条目监控' },
                // { value: '2', label: '上游连接状态' },
                // { value: '3', label: '引擎初始化' },
                // { value: '4', label: '引擎运行状态' },
                // { value: '5', label: 'CDC运行监听' },
                { label: '风险报告结果', value: '6' },
                { label: '风险计算异常', value: '12' },
                { label: '条目同步黑白名单启停', value: '9' },
                { label: '条目同步黑白名单更新', value: '10' },
                { label: '分项授信额度通知', value: '13' },
                { label: '触发提醒类', value: '15' },
            ],
            type: 'func',
            funcBody: value => (value && value.trim() ? noticeTypeStorage[value] : '--'),
        },
        {
            name: '邮件主题',
            val: 'emailSubject',
            align: 'left',
            width: '180px',
            filters: [{ data: '' }],
        },
        {
            name: '通知用户',
            val: 'noticeUser',
            align: 'left',
            filters: [{ data: '' }],
        },
        {
            name: '通知岗位',
            val: 'notifier',
            align: 'left',
            filters: [{ data: '' }],
            // todo
        },
        {
            name: '邮件发送时间',
            val: 'dateTime',
            align: 'center',
            minWidth: '140px',
        },
        {
            name: '邮件发送状态',
            val: 'sendStatus',
            align: 'center',
            minWidth: '140px',
            filters: [
                { label: '发送成功', value: '0' },
                { label: '发送失败', value: '1' },
            ],
            type: 'func',
            funcBody: value => (value && value.trim() ? sendStatusStorage[value] : '--'),
        },
    ];

    // 实际排序参数字段
    private sortEnum: any = {
        recordId: 'N_RECORD_ID',
        ruleId: 'C_RULE_ID',
        ruleName: 'C_RULE_NAME',
        noticeType: 'C_NOTICE_TYPE',
        emailSubject: 'C_EMAIL_SUBJECT',
        noticeUser: 'C_NOTICE_USER',
        dateTime: 'D_DELIVERY_TIME',
        sendStatus: 'C_SEND_STATUS',
        notifier: 'C_NOTIFIER',
    };
    private sortProp: string = ''; // 默认排序字段
    private sortOrder: string = ''; // 默认排序方式
    private sortParam: string = 'D_SEND_DATE desc,D_SEND_TIME desc';

    private checkFiltersParams: string[] = ['noticeType', 'sendStatus']; // 漏斗
    private changeIconCols: any[] = [0, 1, 3, 4, 5]; // 第一列修改筛选图标  漏斗改放大镜

    private searchParams: any = {
        recordId: '',
        // ruleId: '',
        ruleName: '',
        noticeTypeGroup: [],
        emailSubject: '',
        noticeUser: '',
        notifier: '',
        sendStatusGroup: [],
    };

    private recordDetail: any = null;

    created() {}
    mounted() {
        this.getEmailHistoryList();
        this.changeTable();
    }

    private getEmailHistoryList(): void {
        this.loading = true;
        // 永赢项目查看所有发送记录 其他项目默认为当天
        let defaultToday = getConfigItem('WEB_DOCKING') !== 'MAXWEALTH';
        this.$axios({
            method: 'post',
            url: '/notice/monitor/record/listRecords',
            data: { ruleId: this.data.content.ruleId, paging: this.paging, ...this.searchParams, sort: this.sortParam, defaultToday },
        }).then((res: any) => {
            if (res) {
                res.list.forEach(element => {
                    element.dateTime = dateFormat(element.sendDate) + '  ' + timeFormat(element.sendTime);
                    if (element.recordDetail) {
                        element.recordDetail = element.recordDetail
                            .replace('<!DOCTYPE html>\n<html lang="en">\n<head>\n    <meta charset="UTF-8">\n</head>\n<body>\n', '')
                            .replace('\n</body>\n</html>', '');
                    }
                });
                this.dataSource = res.list || [];
                this.paging.total = res.total || 0;
            }
            this.loading = false;
        });
    }

    private handleSort(val): void {
        const { order, property } = val;
        this.sortParam = this.handleSortField(order, property);
        this.paging.currentPage = 1;
        this.getEmailHistoryList();
    }

    private handleFilter({ field, values, datas }): void {
        if (field === 'noticeType' || field === 'sendStatus') {
            this.searchParams[field + 'Group'] = values;
        } else {
            this.searchParams[field] = datas.join('');
        }
        this.paging.currentPage = 1;
        this.getEmailHistoryList();
    }

    private handleRowClick({ row }): void {
        if (row.recordDetail) {
            this.recordDetail = row?.recordDetail;
        } else {
            this.$axios({ method: 'post', url: '/notice/monitor/record/recordDetailById', data: { recordId: row.recordId } }).then((res: any) => {
                if (res) {
                    res = res
                        .replace('<!DOCTYPE html>\n<html lang="en">\n<head>\n    <meta charset="UTF-8">\n</head>\n<body>\n', '')
                        .replace('\n</body>\n</html>', '');
                }
                this.recordDetail = res;
            });
        }
    }

    // 获取排序字段
    private handleSortField(name: string, order: string): string {
        let value = '';
        if (name) {
            value = this.sortEnum[order] + ' ' + name;
            if (order == 'dateTime') {
                value = 'D_SEND_DATE' + ' ' + name + ',' + 'D_SEND_TIME' + ' ' + name;
            }
        }
        return value;
    }

    private getStyle(val: string, value: string): any {
        let color = '';
        if (['sendStatus'].includes(val)) {
            color = value == '0' ? 'green' : value == '1' ? 'red' : '';
        }
        return { color: color };
    }

    // 改变筛选按钮
    changeTable() {
        const _this = this;
        this.$nextTick(() => {
            let iconDom = (_this.$refs['table'] as any).$el.querySelectorAll('.vxe-icon--funnel');
            for (let i = 0; i < iconDom.length; i++) {
                if (this.changeIconCols.includes(i)) {
                    iconDom[i].className = 'vxe-filter--btn el-icon-search';
                }
            }
        });
    }
}
</script>
<style lang="scss" scoped>
#email-history {
    padding: 10px 20px;
    height: calc(100vh - 45px);
    color: #000;
    .el-row {
        height: 50%;

        .my-input {
            margin: 10px;
            width: 150px;
        }
    }

    .html-box {
        border: 1px solid;
    }
}

/deep/ .vxe-table--render-default.border--full .vxe-body--column {
    border: none;
}
</style>
